/*
 * @lc app=leetcode.cn id=654 lang=java
 *
 * [654] 最大二叉树
 */

// @lc code=start

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return buildTree(nums, 0, nums.length);
    }

    private TreeNode buildTree(int[] nums, int left1, int right1) {
        if(right1 - left1 < 1) {
            return null;
        }
        if(right1 - left1 == 1) {
            return new TreeNode(nums[left1]);
        }

        int maxIndex = left1;
        int maxValue = nums[left1];

        for(int i = left1 + 1; i < right1; i++) {
            if(nums[i] > maxValue) {
                maxValue = nums[i];
                maxIndex = i;
            }
        }

        TreeNode root = new TreeNode(maxValue);

        root.left = buildTree(nums, left1, maxIndex);
        root.right = buildTree(nums, maxIndex + 1, right1);
        return root;
    }
}
// @lc code=end

